<script setup>
import { ref, computed, onMounted, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import { getQrCode, getToken } from '@/api/user'
import { useStore } from '@/store'
import { ElMessage } from 'element-plus'

const router = useRouter()
const tokenStore = useStore()

// 二维码信息
const qrCodeInfo = ref({
  "ticket": undefined,
  "expireSeconds": undefined,
  "url": undefined
})
// 登录加载状态
const loading = ref(false)



// 二维码加载状态
const qrCodeLoading = ref(true)
// 二维码是否过期
const qrExpired = ref(false)
// 二维码倒计时
const refreshCountdown = ref(0)

// 轮询定时器
let pollingTimer = null
// 倒计时定时器
let countdownTimer = null

// 过期时间器
const Countdown = (seconds) => {
  // 清除之前的倒计时
  if (countdownTimer) {
    clearTimeout(countdownTimer)
  }
  
  refreshCountdown.value = seconds
  
  if (seconds <= 0) {
    qrExpired.value = true // 倒计时结束
    stopPolling() // 停止轮询
    return
  }

  countdownTimer = setTimeout(() => {
    refreshCountdown.value--
    Countdown(refreshCountdown.value) // 递归调用，传递新的值
  }, 1000)
}

const qrCodeUrl = computed(() => {
  return "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + qrCodeInfo.value.ticket
})

onMounted(() => {
  // 确保组件挂载时没有正在运行的轮询
  stopPolling()
  let uuid = crypto.randomUUID();
  getQrCode(uuid).then(res => {
    qrCodeInfo.value = res.data
    qrCodeLoading.value = false
    qrExpired.value = false
    Countdown(qrCodeInfo.value.expireSeconds)
    // Countdown(5)
    // 只有在二维码获取成功后才开始轮询
    pollingCheckQrCode(uuid)
  })
})
const pollingCheckQrCode = (uuid) => {
  // 避免重复开启多个轮询
  if (pollingTimer) return
  pollingTimer = setInterval(() => {
    getToken(uuid).then(res => {
      if (res.data && res.code == 200) {
        // 保存 token
        tokenStore.setToken(res.data.token)
        // 清除轮询定时器
        clearInterval(pollingTimer)
        pollingTimer = null
        // 登录成功提示
        ElMessage.success('登录成功')
        // 跳转到首页
        router.push('/')
      }
    }).catch(err => {
      console.error('轮询二维码状态出错:', err)
    })
  }, 3000) // 每 5 秒轮询一次
}
// 刷新二维码
const refreshQrCode = () => {
  qrCodeLoading.value = true
  // 先停止之前的轮询
  stopPolling()
  let uuid = crypto.randomUUID()
  getQrCode(uuid).then(res => {
    qrCodeInfo.value = res.data
    qrCodeLoading.value = false
    qrExpired.value = false
    Countdown(qrCodeInfo.value.expireSeconds)
    // 只有在二维码获取成功后才开始轮询
    pollingCheckQrCode(uuid)
  })
}

const stopPolling = () => {
  if (pollingTimer) {
    clearInterval(pollingTimer)
    pollingTimer = null
  }
}

onBeforeUnmount(() => {
  if (pollingTimer) clearInterval(pollingTimer)
  if (countdownTimer) clearTimeout(countdownTimer)
})
</script>

<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-title">
        <h2>后台管理系统</h2>
      </div>

      <div class="qrcode-container">
        <div class="qrcode-box" :class="{ 'qrcode-loading': qrCodeLoading }">
          <el-image v-if="qrCodeUrl && !qrCodeLoading" :src="qrCodeUrl" alt="登录二维码" class="qrcode-img" fit="contain" />
          <img v-else-if="!qrCodeUrl && !qrCodeLoading" src="@/assets/images/user.png" alt="二维码加载失败"
            class="qrcode-img" />
          <el-skeleton v-if="qrCodeLoading" :rows="5" animated />
        </div>

        <div class="qrcode-info">
          <p class="qrcode-tip">请使用手机扫描二维码登录</p>
          <p class="qrcode-expired" v-if="qrExpired">
            <el-icon>
              <Warning />
            </el-icon>
            二维码已过期
          </p>
        </div>

        <div class="qrcode-actions">
          <el-button v-if="qrExpired" type="primary" :icon="qrCodeLoading ? 'Loading' : 'Refresh'" :loading="qrCodeLoading"
            @click="refreshQrCode">
            刷新二维码
          </el-button>
        </div>

        <div class="login-footer">
          <p>扫码登录更安全</p>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="less">
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  width: 100%;
  background-color: #f5f7fa;
  background-image: linear-gradient(120deg, #e0c3fc 0%, #8ec5fc 100%);
}

.login-box {
  width: 400px;
  padding: 30px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.login-title {
  text-align: center;
  margin-bottom: 30px;

  h2 {
    font-size: 24px;
    color: #303133;
    margin: 0;
  }
}

.login-button {
  width: 100%;
}

.qrcode-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px 0;
}

.qrcode-box {
  width: 200px;
  height: 200px;
  margin-bottom: 20px;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
  transition: all 0.3s ease;

  &.qrcode-loading {
    background-color: #f8f9fa;
  }
}

.qrcode-img {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.qrcode-info {
  text-align: center;
  margin-bottom: 20px;
}

.qrcode-tip {
  color: #606266;
  margin-bottom: 10px;
  font-size: 14px;
}

.qrcode-countdown {
  color: #409EFF;
  font-size: 14px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 5px;
}

.qrcode-expired {
  color: #F56C6C;
  font-size: 14px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 5px;
}

.qrcode-actions {
  margin-bottom: 20px;
}

.refresh-button {
  background-color: #F56C6C;
  border-color: #F56C6C;
  font-weight: bold;
  animation: pulse 1.5s infinite;
}

@keyframes pulse {
  0% {
    box-shadow: 0 0 0 0 rgba(245, 108, 108, 0.4);
  }
  70% {
    box-shadow: 0 0 0 10px rgba(245, 108, 108, 0);
  }
  100% {
    box-shadow: 0 0 0 0 rgba(245, 108, 108, 0);
  }
}

.login-footer {
  margin-top: 20px;
  text-align: center;
  color: #909399;
  font-size: 12px;
}
</style>